package com.sky.controller;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.HttpClientErrorException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.util.regex.*;

@RestController
public class ImageAnnotationController {

    private final RestTemplate restTemplate = new RestTemplate();

    // 配置超时时间（毫秒）
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 10000;

    @PostMapping(value = "/annotate", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<byte[]> annotateImage(
            @RequestParam("url") String imageUrl,
            @RequestParam("bbox") String bboxString) {

        try {
            // 1. 下载图片
            byte[] imageBytes = downloadImage(imageUrl);

            // 2. 解析bbox坐标
            int[] coords = parseBoundingBox(bboxString);
            int x = coords[0], y = coords[1], width = coords[2] - x, height = coords[3] - y;

            // 3. 处理图片
            byte[] processedImage = processImage(imageBytes, x, y, width, height);

            // 4. 返回处理后的图片
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=annotated.png")
                    .contentType(MediaType.IMAGE_PNG)
                    .body(processedImage);

        } catch (InvalidBboxException e) {
            return ResponseEntity.badRequest().body(("坐标格式错误: " + e.getMessage()).getBytes());
        } catch (ImageProcessingException e) {
            return ResponseEntity.badRequest().body(("图片处理失败: " + e.getMessage()).getBytes());
        } catch (ImageDownloadException e) {
            return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
                    .body(("图片下载失败: " + e.getMessage()).getBytes());
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(("服务器错误: " + e.getMessage()).getBytes());
        }
    }

    private byte[] downloadImage(String imageUrl) throws ImageDownloadException {
        try {
            // 设置超时
            restTemplate.getRequestFactory().createRequest(URI.create(imageUrl), HttpMethod.GET)
                    .getHeaders().set("User-Agent", "Mozilla/5.0");

            ResponseEntity<byte[]> response = restTemplate.exchange(
                    imageUrl,
                    HttpMethod.GET,
                    null,
                    byte[].class);

            if (response.getStatusCode() != HttpStatus.OK || response.getBody() == null) {
                throw new ImageDownloadException("图片服务返回状态: " + response.getStatusCode());
            }
            return response.getBody();
        } catch (HttpClientErrorException e) {
            throw new ImageDownloadException("HTTP错误: " + e.getStatusCode() + " - " + e.getStatusText());
        } catch (Exception e) {
            throw new ImageDownloadException("下载失败: " + e.getMessage());
        }
    }

    private byte[] processImage(byte[] imageBytes, int x, int y, int width, int height)
            throws ImageProcessingException {

        try (ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            // 1. 读取图片
            BufferedImage originalImage = ImageIO.read(bais);
            if (originalImage == null) {
                throw new ImageProcessingException("无法解析图片格式");
            }

            // 2. 验证坐标
            if (x < 0 || y < 0 || width <= 0 || height <= 0 ||
                    (x + width) > originalImage.getWidth() ||
                    (y + height) > originalImage.getHeight()) {
                throw new ImageProcessingException(String.format(
                        "坐标超出范围 (图片尺寸: %dx%d, 标注区域: [%d, %d, %d, %d])",
                        originalImage.getWidth(), originalImage.getHeight(),
                        x, y, x + width, y + height
                ));
            }

            // 3. 创建副本
            BufferedImage annotatedImage = new BufferedImage(
                    originalImage.getWidth(),
                    originalImage.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);

            Graphics2D g2d = annotatedImage.createGraphics();

            // 4. 绘制原始图片
            g2d.drawImage(originalImage, 0, 0, null);

            // 5. 设置标注样式
            g2d.setColor(new Color(255, 0, 0, 200)); // 半透明红色
            g2d.setStroke(new BasicStroke(4)); // 4像素宽
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            // 6. 绘制边界框
            g2d.drawRect(x, y, width, height);

            // 7. 添加角标
            int cornerSize = 24;
            g2d.fillRect(x, y, cornerSize, cornerSize);
            g2d.setColor(Color.WHITE);
            g2d.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
            g2d.drawString("题", x + 6, y + 18);

            // 8. 添加区域标签
            g2d.setColor(new Color(220, 0, 0));
            g2d.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
            g2d.drawString("题目区域", x + cornerSize + 10, y + 22);

            g2d.dispose();

            // 9. 输出PNG
            ImageIO.write(annotatedImage, "png", baos);
            return baos.toByteArray();
        } catch (Exception e) {
            throw new ImageProcessingException("处理失败: " + e.getMessage());
        }
    }

    private int[] parseBoundingBox(String bboxString) throws InvalidBboxException {
        try {
            // 支持多种格式:
            // 1. XML格式: <bbox>13 12 904 922</bbox>
            // 2. 纯数字格式: 13,12,904,922
            // 3. 空格分隔: "13 12 904 922"
            Pattern pattern = Pattern.compile(
                    "(?:<bbox>\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*</bbox>)|" +
                            "(?:(\\d+)[, ]+(\\d+)[, ]+(\\d+)[, ]+(\\d+))"
            );
            Matcher matcher = pattern.matcher(bboxString);

            if (matcher.find()) {
                if (matcher.group(1) != null) { // XML格式
                    return new int[] {
                            parseInt(matcher.group(1)),
                            parseInt(matcher.group(2)),
                            parseInt(matcher.group(3)),
                            parseInt(matcher.group(4))
                    };
                } else { // 数字格式
                    return new int[] {
                            parseInt(matcher.group(5)),
                            parseInt(matcher.group(6)),
                            parseInt(matcher.group(7)),
                            parseInt(matcher.group(8))
                    };
                }
            }
            throw new InvalidBboxException("无法识别的坐标格式");
        } catch (Exception e) {
            throw new InvalidBboxException("解析错误: " + e.getMessage());
        }
    }

    private int parseInt(String value) throws NumberFormatException {
        int result = Integer.parseInt(value);
        if (result < 0) throw new NumberFormatException("坐标不能为负数");
        return result;
    }

    // 自定义异常类
    private static class InvalidBboxException extends Exception {
        public InvalidBboxException(String message) { super(message); }
    }

    private static class ImageProcessingException extends Exception {
        public ImageProcessingException(String message) { super(message); }
    }

    private static class ImageDownloadException extends Exception {
        public ImageDownloadException(String message) { super(message); }
    }
}
